/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sequencer.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import sequencer.GenerationEngine;
//import sequencer.db.Activity;
import sequencer.db.Schedule;
//import sequencer.db.User;
import sequencer.db.util.DataManager;

/**
 *
 * @author Daniel Rogers
 */
public class GeneratorWindow extends javax.swing.JDialog
        implements PropertyChangeListener {

    /**
     * Creates new form GeneratorWindow
     */
    private GeneratorWindow() {
        initComponents();
    }

    /**
     *
     * @param manager
     */
    public GeneratorWindow(DataManager manager) {
        initComponents();
        //userId = user;
        this.manager = manager;
        //System.out.println(userId);

        setLocationRelativeTo(null);
        //calculating = false;
        //jProgressBar1.setIndeterminate(true);
    }

    private void showScheduleActivities(Schedule s) {

        Integer[] temp = s.getActivities().toArray(new Integer[0]);
        //Activity[] activities;

        //System.out.println("uacts: " + Arrays.toString(temp));
        if (temp.length > 0) {
            //fetch all activities
            //activities = new Activity[temp.length];
            //for (int i = 0; i < temp.length; ++i) {
            //    activities[i] = (Activity) MongoHelper.fetch(new Activity(temp[i]),
            //            MongoHelper.ACTIVITY_COLLECTION);
            //}

            activityNames = new String[temp.length];

            //get the names of the activities for our list
            for (int i = 0; i < temp.length; ++i) {
                //System.out.println("a" + i + "name: " + activities[i].getName());
                activityNames[i] = manager.getActivityById(temp[i]).getName();
            }

            //System.out.println("anames: " + Arrays.toString(getActivityNames));
            //sort alphabetical
            if (activityNames.length > 1) {
                Arrays.sort(activityNames);
            }

        }

        if (activityList != null && activityNames != null) {
            activityList.setModel(new javax.swing.AbstractListModel() {
                String[] strings = activityNames;

                @Override
                public int getSize() {
                    return strings.length;
                }

                @Override
                public Object getElementAt(int i) {
                    return strings[i];
                }
            });
            this.repaint();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        jLabel1 = new javax.swing.JLabel();
        desiredResultsBox = new javax.swing.JComboBox();
        generateButton = new javax.swing.JButton();
        jProgressBar1 = new javax.swing.JProgressBar();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        activityList = new javax.swing.JList();
        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Sequencer: Generator");
        setModalExclusionType(java.awt.Dialog.ModalExclusionType.APPLICATION_EXCLUDE);
        setResizable(false);
        addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                formPropertyChange(evt);
            }
        });

        jLabel1.setText("Desired Number of Results:");

        desiredResultsBox.setModel(new javax.swing.DefaultComboBoxModel(options));

        generateButton.setText("Generate");
        generateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                generateButtonActionPerformed(evt);
            }
        });

        jProgressBar1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jProgressBar1PropertyChange(evt);
            }
        });

        jLabel2.setText("Preparing to generate a schedule...");

        jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jList1ValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jList1);

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jList1, org.jdesktop.beansbinding.ELProperty.create("${selectedElement}"), jLabel3, org.jdesktop.beansbinding.BeanProperty.create("text"), "");
        bindingGroup.addBinding(binding);

        jScrollPane2.setViewportView(activityList);

        jButton2.setText("Use Schedule");
        jButton2.setEnabled(false);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton1.setText("Cancel");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel1)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(desiredResultsBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(75, 75, 75))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addComponent(generateButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jButton2)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jButton1)))
                    .addComponent(jLabel2)
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(desiredResultsBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(generateButton)
                            .addComponent(jButton2)
                            .addComponent(jButton1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void generateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_generateButtonActionPerformed
        //calculating = true;

        jLabel2.setText("Generating...");
        generateButton.setSelected(true);
        //get the real number of results
        int selected = desiredResultsBox.getSelectedIndex();
        if (selected != -1) {
            selected = Integer.parseInt(options[selected]);
        } else {
            selected = 1;
        }
        //System.out.println("id:gen_pre_calc " + userId);
        //GenerationEngine g = new GenerationEngine(this);
        //generated = g.calculateSchedules(manager, selected,
        //       jProgressBar1);
        generator = new GenerationEngine(this, manager,
                selected);
        generator.addPropertyChangeListener(this);
        generator.execute();
        //System.out.println(Arrays.toString(generated));

    }//GEN-LAST:event_generateButtonActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        //set up schedule here
        //get which one they wish to use
        int indx = jList1.getSelectedIndex();
        if (indx == -1) {
            indx = 0;
        }

        /*MongoHelper.save(generated[indx], MongoHelper.SCHEDULE_COLLECTION);

         User u = (User) MongoHelper.fetch(new User(userId),
         MongoHelper.USER_COLLECTION);
         u.setSchedule(generated[indx].getId());
         MongoHelper.save(u, MongoHelper.USER_COLLECTION);*/
        manager.updateSchedule(generated[indx]);

        //then dispose of the window
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList1ValueChanged
        int indx = jList1.getSelectedIndex();
        //System.out.println(generated[indx].getActivities());
        if(indx < 0) {
            indx = 0;
        }
        showScheduleActivities(generated[indx]);
    }//GEN-LAST:event_jList1ValueChanged

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void formPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_formPropertyChange
        //jProgressBar1.setValue(50);
    }//GEN-LAST:event_formPropertyChange

    private void jProgressBar1PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jProgressBar1PropertyChange
    }//GEN-LAST:event_jProgressBar1PropertyChange

    /**
     *
     * @param pce
     */
    @Override
    public void propertyChange(PropertyChangeEvent pce) {
        //System.out.println(pce.getNewValue().getClass());
        if ("progress".equals(pce.getPropertyName())) {
            int progress = (Integer) pce.getNewValue();
            jProgressBar1.setValue(progress);
        } else if (generator.isDone()) {
            generated = generator.getSchedules();
            
            schedules = new String[generated.length];
            for (int i = 0; i < schedules.length; ++i) {
                schedules[i] = generated[i].getName();
            }
            //display schedules
            jList1.setModel(new javax.swing.AbstractListModel() {
                String[] strings = schedules;

                @Override
                public int getSize() {
                    return strings.length;
                }

                @Override
                public Object getElementAt(int i) {
                    return strings[i];
                }
            });

            activityList.setSelectedIndex(0);
            jProgressBar1.setValue(99);

            jLabel2.setText("Generation complete");
            jList1.setSelectedIndex(0);
            jButton2.setEnabled(true);
            //calculating = false;
        }
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GeneratorWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GeneratorWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GeneratorWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GeneratorWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new GeneratorWindow().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList activityList;
    private javax.swing.JComboBox desiredResultsBox;
    private javax.swing.JButton generateButton;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JList jList1;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    //Integer userId;
    String[] options = new String[]{"1"};//, "5", "10"};
    String[] schedules;
    String[] activityNames;
    Schedule[] generated;
    DataManager manager;
    //boolean calculating;
    GenerationEngine generator;
}

